from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import os
import logging

from app.core.config import settings
from app.core.logger import setup_logging
from app.api.api_v1.api import api_router

# 设置日志配置
logger = setup_logging()

def create_app() -> FastAPI:
    """
    创建FastAPI应用实例
    """
    logger.info(f"开始创建 {settings.PROJECT_NAME} 应用实例")
    
    app = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.PROJECT_DESCRIPTION,
        version=settings.VERSION,
        docs_url="/docs" if settings.DEBUG else None,
        redoc_url="/redoc" if settings.DEBUG else None,
    )

    # 设置CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 添加路由
    app.include_router(api_router, prefix=settings.API_PREFIX)
    
    # 配置静态文件服务
    uploads_dir = os.path.abspath("uploads")
    if os.path.exists(uploads_dir):
        app.mount("/uploads", StaticFiles(directory=uploads_dir), name="uploads")
    else:
        logger.warning(f"上传目录不存在: {uploads_dir}")

    @app.get("/")
    async def root():
        return {"message": "Welcome to MCP Market API"}

    @app.get("/health")
    async def health_check():
        return {"status": "healthy"}
    
    logger.info(f"{settings.PROJECT_NAME} 应用实例创建完成")
    return app 